package com.kingdee.openimport.patch_service.controller;

import com.kingdee.openimport.patch_service.exception.PatchException;
import com.kingdee.openimport.patch_service.model.PatchVersion;
import com.kingdee.openimport.patch_service.service.ICheckService;
import com.kingdee.openimport.patch_service.service.IPatchMessageService;
import com.kingdee.openimport.patch_service.service.IPatchVersionService;
import com.kingdee.openimport.patch_service.service.IRedisCacheService;
import com.kingdee.openimport.patch_service.util.Result;
import com.kingdee.openimport.patch_service.util.ResultUtil;
import com.kingdee.openimport.patch_service.vo.PatchMsg;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * Created by Niki on 2018/5/8 10:29
 */
@RestController()
@RequestMapping("/version")
public class PatchVersionController {
    @Resource
    IPatchVersionService patchVersionService;
    @Resource
    IRedisCacheService redisCacheService;
    @Resource
    ICheckService checkService;
    @Resource
    IPatchMessageService patchMessageService;

    /**
     * 创建一条补丁版本
     *
     * @param version
     * @param description
     * @return
     */
    @PostMapping(value = "/create/{version}/{description}")
    public Result createVersion(@PathVariable String version, @PathVariable String description) {
        PatchVersion $version = new PatchVersion();
        $version.setVersion(version);
        $version.setDescription(description);
        $version.setDate(new Date());
        patchVersionService.createPatchVersion($version);

        //刷新缓存
        redisCacheService.setLatesVersion(version);
        redisCacheService.addExistVersion(version);
        return ResultUtil.success();
    }

    /**
     * 查询最近的版本号
     *
     * @param size
     * @return
     */
    @GetMapping(value = "/latest/{size}")
    public Result getLatestVersion(@PathVariable int size) {
        if (size <= 0) {
            size = 1;
        } else if (size > 10) {
            //仅查询最近10条记录
            size = 10;
        }
        List<String> versions = patchVersionService.findLatestVersion(size);
        return ResultUtil.success(versions);
    }

    /**
     * 发起打补丁通知
     * @param version
     * @return
     * @throws PatchException
     */
    @GetMapping(value="/send/msg/{version}")
    public Result sendPatchMsg(@PathVariable String version) throws PatchException {
        checkService.checkVersion(version);

        patchMessageService.sendPatchMsg(version);
        return ResultUtil.success();
    }
}
